package com.eu.ebpm.engine.cmd.pvm;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eu.ebpm.engine.entity.deploy.Deploy;
import com.eu.ebpm.engine.entity.deploy.Mission;
import com.eu.ebpm.engine.entity.deploy.Transfer;
import com.eu.ebpm.engine.entity.history.HisExecution;
import com.eu.ebpm.engine.entity.history.HisTask;
import com.eu.ebpm.engine.entity.runtime.Execution;
import com.eu.ebpm.engine.entity.runtime.TaskEntity;
import com.eu.ebpm.engine.init.EbpmCache;
import com.eu.ebpm.engine.repository.ExecutionRepository;
import com.eu.ebpm.engine.repository.HisTaskRepository;

/**
 * @author 王晓华
 */
@Component
public class SubStartEventIntoCommand {

	@Autowired
	private ExecutionRepository executionRepository;
	
	@Autowired
	private HisTaskRepository hisTaskRepository;

	public void execute(Mission subStartEventMission, TaskEntity task, Transfer nextTransfer) {

		Deploy deploy = EbpmCache.getDeployByKey(subStartEventMission.getName());

		// 1、添加流程执行
		Execution subExecution = new Execution(deploy.getName(), deploy.getDesc(), null, deploy.getDesc(), deploy.getId(), new Date(), task.getExecutionId(), task.getRootExecutionId());
		executionRepository.insert(subExecution);
		
		// 2、插入历史流程表
		executionRepository.insertHisExecution(new HisExecution(subExecution.getId(), subExecution.getName(), subExecution.getDesc(), subExecution.getBusinessKey(), subExecution.getDeployId(),
				new Date(), null, true, task.getExecutionId(), task.getRootExecutionId()));

		// 3、插入历史任务表
		hisTaskRepository.insert(new HisTask(subStartEventMission.getType(), subStartEventMission.getName(), subStartEventMission.getDesc(), nextTransfer.getName(), subExecution.getId(), task
				.getRootExecutionId(), subStartEventMission.getId(), null, null, new Date(), new Date()));
		
		// 4、将当前流程ID设置为子流程ID
		task.setExecutionId(subExecution.getId());

	}

}
